import { useState, useEffect } from "react";
import TextLoop from "../../components/Text_Carousel";
import Slideshow from "../../components/Slideshow";
import FloatingBall from "../../components/FloatingBall";
import { Tabbar } from "react-vant";
import { Mask } from "antd-mobile";
import { HomeO, LabelO } from "@react-vant/icons";
import { Swiper } from "react-vant";
import "@/css/show.less";
import { useNavigate, useParams } from "react-router-dom";
import instance from "../utils/https";
import LeaveMessage from "./page/LeaveMessage";
import SupportContestant from "./page/SupportContestant";
import { Toast } from "antd-mobile";
import header from "./page/header.svg";
import {config} from '../../components/Share'
export default function Show() {
  const { id } = useParams();
  const user_id = localStorage.getItem("_id");
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [name, setName] = useState("/home");
  const [userRank, setUserRank] = useState(0);
  const [preVote, setPreVote] = useState(0);
  const [isOpen, setIsOpen] = useState(false);

  interface UserInfoResponse {
    user: {
      mark: string;
      name: string;
      voteNum: number;
      vote: number;
      visitNum: number;
      avtor: string;
      gender: boolean;
      age: number;
      positionName: string;
      introduce: string;
    };
    userRank: number;
    preVote: number;
  }

  interface Activity {
    _id: string;
    accumulatedNum: number;
    announcement: string;
    endTime: string;
    isStart: boolean;
    joinNum: number;
    rule: string;
    startTime: string;
    title: string;
    visitNum: number;
    __v: number;
  }

  const [personalInfo, setPersonalInfo] = useState({
    mark: "",
    name: "",
    ranking: NaN,
    votes: NaN,
    gapToFirst: NaN,
    imageUrl: "",
    positionName: "",
    introduce: "",
  });

  interface Message {
    avtor: string;
    name: string;
    content: string;
    phone: string;
    startTime: string;
    audit: boolean;
  }
  const [messageList , setMessageList] = useState ([
    // {
    //   avtor:
    //     "https://thirdwx.qlogo.cn/mmopen/vi_32/NCxzLicvgyulMicibG7nEPwciaWibCgCh33N6NhcdAeVVbhSgeygcl91oToaxUVAN8icWwSHR8qaBzhvdJQQ7Q1hS9e10mZASS9ZQic2b2Ut7AbkWA/132",
    //   name: "安",
    //   content: "ddd",
    //   phone: "123",
    //   startTime: "2024-12-09 15:27:30",
    //   audit: true,
    // },
  ]);

 
  const goto = (v: string) => {
    setName(v);
    navigate(v);
  };
  const getDetail = async () => {
    const res: UserInfoResponse = await instance.get(
      `detail/getUserInfo?_id=${id}`
    );
    setPersonalInfo({
      mark: res.user.mark,
      name: res.user.name,
      ranking: res.user.voteNum,
      votes: res.user.vote,
      gapToFirst: res.user.visitNum,
      imageUrl: res.user.avtor,
      positionName: res.user.positionName,
      introduce: res.user.introduce,
    });
    setUserRank(res.userRank);
    setPreVote(res.preVote);
  };

  const getmassage = async () => {
    const res = await instance.get(
      `detail/getappComment?cid=${id}&userId=${user_id}`
    );

    setMessageList(res.data);
  };

  interface VoteResponse {
    message: string;
    totalVotes: number;
    remainingVotes: number;
  }

  // 投票功能
  const vote = async () => {
    try {
      const res: VoteResponse = await instance.post("/homePage/udvote", {
        voter_id: user_id,
        candidate_ids: [id],
        vtime: Date.now(),
      });
      if (res) {
        getDetail();
        Toast.show({
          content: `已投${res.totalVotes}票，今日可投剩余${res.remainingVotes}票`,
        });
      }
       
    } catch (error:any) {
      // if(error.response?.data?.message === "每天只能投十次"){
      //   setIsOpen(true);
      // }
      Toast.show({
        content: "每天只能投十票",
      })
    }
  };

  const [activityList, setActivityList] = useState<Activity | null>(null);

  const getActivityInfo = async () => {
    try {
      const res: any = await instance.get("/homePage/getVisit");
      setActivityList(res.data || null); // 假设只使用第一个活动
    } catch (error) {
      console.error("获取活动信息失败", error);
    }
  };

  useEffect(() => {
    getDetail();
    getmassage();
    getActivityInfo();
  }, []);

  useEffect(() => {
    if (personalInfo) {
      console.log('个人信息已加载，自动执行分享', personalInfo);
      config({
        title: personalInfo.name,
        desc: '我在参加调味大师名人堂快来投票吧,' + personalInfo.positionName + personalInfo.name,
        link: window.location.href,
        imgUrl: personalInfo.imageUrl,
      });
    }
  }, [personalInfo]); // 当 personalInfo 更新时，自动执行分享

  return (
    <div className="box">
      <TextLoop activityList={activityList}></TextLoop>
      <Slideshow></Slideshow>

      <p className="p_text">
        <span>{personalInfo.mark}号</span>
        <span style={{ marginLeft: "10px" }}>{personalInfo.name}</span>
      </p>
      {/* 数据展示 */}
      <div className="presentation">
        <div>
          <p className="yellow">{userRank}</p>
          <p className="gray">当前排名</p>
        </div>
        <div>
          <p className="yellow">{personalInfo.votes}</p>
          <p className="gray">当前票数</p>
        </div>
        <div>
          <p className="yellow">{preVote}票</p>
          <p className="gray">距前一名相差</p>
        </div>
      </div>
      {/* 详细信息 */}
      <div className="detail_info">
        <p style={{color:'#f8c588'}}>{personalInfo.name}</p>
        <p style={{color:'#FFD700'}}>{personalInfo.positionName}</p>
        <div style={{width:'80%'}}>{personalInfo.introduce}</div>
        <img
          src={personalInfo.imageUrl}
          style={{ width: "80%", borderRadius: "10px" }}
          alt=""
        />
      </div>

      <div className="btns">
        <div className="btn">
          {id && <LeaveMessage cid={id} onGetmassage={getmassage} />}
        </div>

        <div
          className="btn"
          onClick={() => {
            navigate("/home");
          }}
        >
          返回首页
        </div>

        <div className="btn">
          <div onClick={()=>{setIsOpen(true)}} style={{fontSize:'17px',color:"rgb(230, 124, 18)"}}>为他打call</div>
          {isOpen && <SupportContestant cid={id} onClose={(isOpen2) => setIsOpen(isOpen2)} />}
        </div>
      </div>
      <Mask
        visible={visible}
        onMaskClick={() => setVisible(false)}
        opacity="thick"
      >
        <div className="demo-swiperr">
          <Swiper>
            <Swiper.Item>
              <div className="one">
                <p style={{ fontSize: "14px", margin: "20px 0" }}>
                  2020第三届调味大师名人堂评选
                </p>
                <img src={personalInfo.imageUrl} alt="" />
                <p style={{ fontSize: "14px", margin: "10px 0" }}>
                  我是{personalInfo.mark}号选手{personalInfo.name}
                </p>
                <p style={{ fontSize: "14px", margin: "10px 0" }}>
                  请您为我投票吧
                </p>
              </div>
            </Swiper.Item>
          </Swiper>
        </div>
      </Mask>

      <div className="message-list">
        {messageList.map((item:Message, index) => (
          <div className="message-item" key={index}>
            <div className="message-header">
              <img src={header} alt="" className="avator" />
              {/* <p className="nickname">{item?.phone?.slice(-4)}用户</p> */}
            </div>
            <div className="message-content">
              <p style={{ width: "100%", wordWrap: "break-word" }}>
                {item.content}
              </p>
            </div>
            <div className="message-footer">
              <p className="time">
                {new Date(item.startTime).toLocaleString()}
              </p>
              <p className="approved">
                {item.audit ? "" : "[该留言尚未审核，仅自己可见]"}
              </p>
            </div>
          </div>
        ))}
      </div>

      <div className="footer">
        <Tabbar
          value={name}
          onChange={(v) => goto(v as string)}
          inactiveColor="rgb(235, 202, 142)"
          activeColor="rgb(235, 202, 142)"
          style={{ background: "black", width: "100%" }}
        >
          <Tabbar.Item
            name="/app/layout/home"
            icon={<HomeO />}
            style={{ background: "rgb(80,77,84)" }}
          >
            首页
          </Tabbar.Item>
          <Tabbar.Item style={{ background: "rgb(80,77,84)" }}>
            <div
              style={{
                width: "120px",
                height: "120px",
                backgroundColor: "rgb(235, 202, 142)",
                borderRadius: "50%",
                position: "relative",
                top: -40,
                color: "white",
                textAlign: "center",
                lineHeight: "120px",
                fontSize: "24px",
              }}
              onClick={() => {
                vote();
              }}
            >
              投票
            </div>
          </Tabbar.Item>
          <Tabbar.Item
            name="/app/layout/ranking"
            icon={<LabelO />}
            style={{ background: "rgb(80,77,84)" }}
          >
            排名
          </Tabbar.Item>
        </Tabbar>
      </div>
      <FloatingBall></FloatingBall>
      <div
        className="floating-ballr"
        onClick={() => {
          setVisible(true);
        }}
      >
        海报
      </div>
    </div>
  );
}
